import numpy as np
from datetime import datetime, timedelta

class OrbitCalculator:
    """卫星轨道计算器"""
    
    def __init__(self):
        # 地球参数
        self.earth_radius = 6371  # km
        self.mu = 3.986004418e5  # km³/s² (地球引力常数)
        
        # 轨道参数
        self.altitude = 550  # km
        self.inclination = 53  # degrees
        self.period = None
        self.semi_major_axis = None
        
        # 时间参数
        self.start_time = datetime.now()
        self.elapsed_time = 0
        
    def set_parameters(self, altitude, inclination):
        """设置轨道参数"""
        self.altitude = altitude
        self.inclination = np.radians(inclination)
        self.semi_major_axis = self.earth_radius + self.altitude
        self.period = 2 * np.pi * np.sqrt(self.semi_major_axis**3 / self.mu)
        
    def get_current_position(self):
        """获取当前卫星位置"""
        # 简化的轨道计算（圆形轨道）
        self.elapsed_time += 10  # 假设每步进10秒
        
        # 计算平均角速度
        n = 2 * np.pi / self.period
        
        # 计算当前角度（考虑地球自转）
        theta = n * self.elapsed_time
        
        # 计算卫星在轨道平面内的坐标
        x_orb = self.semi_major_axis * np.cos(theta)
        y_orb = self.semi_major_axis * np.sin(theta)
        z_orb = 0
        
        # 转换为地心坐标系
        # 应用轨道倾角
        x_ecef = x_orb * np.cos(self.inclination)
        y_ecef = y_orb
        z_ecef = x_orb * np.sin(self.inclination)
        
        # 计算经纬度
        latitude = np.degrees(np.arcsin(z_ecef / self.semi_major_axis))
        longitude = np.degrees(np.arctan2(y_ecef, x_ecef))
        
        return {
            'x': x_ecef,
            'y': y_ecef,
            'z': z_ecef,
            'latitude': latitude,
            'longitude': longitude,
            'altitude': self.altitude,
            'velocity': np.sqrt(self.mu / self.semi_major_axis)
        }
    
    def get_ground_track(self, duration_hours=2):
        """获取地面轨迹"""
        track = []
        original_time = self.elapsed_time
        
        for t in range(0, int(duration_hours * 3600), 60):  # 每分钟一个点
            self.elapsed_time = t
            pos = self.get_current_position()
            track.append({
                'latitude': pos['latitude'],
                'longitude': pos['longitude'],
                'time': t
            })
        
        self.elapsed_time = original_time
        return track
    
    def get_coverage_area(self, position, min_elevation=10):
        """计算覆盖区域"""
        # 计算最大覆盖角
        earth_central_angle = np.arccos(
            self.earth_radius * np.cos(np.radians(min_elevation)) / 
            (self.earth_radius + self.altitude)
        )
        
        # 计算覆盖半径
        coverage_radius = self.earth_radius * earth_central_angle
        
        return {
            'center_lat': position['latitude'],
            'center_lon': position['longitude'],
            'radius': np.degrees(coverage_radius),
            'area': 2 * np.pi * self.earth_radius**2 * (1 - np.cos(earth_central_angle))
        }